#include<MatrixLed.h>

MatrixLed::MatrixLed(byte dataPin,byte clkPin,byte csPin){
    lc=LedControl(dataPin,clkPin,csPin,1);
}

void MatrixLed::init(){
    lc.shutdown(0,false);
    lc.setIntensity(0,1);
    plane = 0;
    isnewenemy = 1;
    
}

void MatrixLed::display(){
    if(millis()-lasttime >=fireIntervel)
    {
    //清零
    for(int i=0;i<8;i++)
        matrix[i]=0;

    //显示小飞机
    matrix[0]= (1<<plane) | matrix[0];
    matrix[1]= (1<<plane) | matrix[0];
    if(plane==0)                          
        matrix[0]= (1<<1) | matrix[0];
    else if (plane == 7)
        matrix[0]= (1<<6) | matrix[0];
    else
    {
        matrix[0] = (1<<(plane +1)) | matrix[0];
        matrix[0] = (1<<(plane -1)) | matrix[0];
    }

     //显示敌机
     if(isnewenemy)
     {
         randomSeed(millis());
         enemy = random(8);
         isenemy=1;
         isnewenemy = 0;
     }
    if(isenemy)
    {
        matrix[7] =  (1<<enemy) | matrix[7];  
    }
     

     if(this->fired)
    {
 //       if(millis()-lasttime >= this->fireIntervel)
  //      {
            matrix[this->firey]= matrix[this->firey] | (1<<this->firex);
            if(this->firey<6)
                this->firey++;
            else
            {
                if(this->firex == enemy)
                {
                     isenemy =0;
                     isnewenemy =1;
                }
                   
                this->fired=0;
            }
  //          this->lasttime =millis();
 //       }
    }

    for(int i=0;i<8;i++)
        this->lc.setRow(0,i,this->matrix[i]);
    lasttime =millis();
    }
}

void MatrixLed::moveleft(){
    if(this->plane<=6)
        this->plane++;    
}

void MatrixLed::moveright(){
    if(this->plane>=1)
        this->plane--;
}

void MatrixLed::setplane(byte location)
{
    if(location<=7 && location>=0)
        plane = location;
}

void MatrixLed::getfire()
{
    this->fired=1;
    this->firex=this->plane;
    this->firey=1;
    this->lasttime=millis();
}